package com.daixin.blog.controller;

import com.daixin.blog.dto.AccessTokenDTO;
import com.daixin.blog.dto.GiteeUser;
import com.daixin.blog.dto.GithubUser;
import com.daixin.blog.model.User;
import com.daixin.blog.provider.GiteeProvider;
import com.daixin.blog.provider.GithubProvider;
import com.daixin.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * Author daixin
 */
@Controller
@ResponseBody
public class AuthorizeController {
    @Autowired
    private GithubProvider githubProvider;
    @Autowired
    private UserService userService;
    @Value("${github.client.id}") //定义Github oAuth时的三个值，为了方便在文件中修改使用@Value标签定义
    private String clientId;
    @Value("${github.client.secret}")
    private String clientSecret;
    @Value("${github.redirect.uri}")
    private String redirectUri;
    @Autowired
    private GiteeProvider giteeProvider;
    @Value("${gitee.client.id}") //定义Gitee oAuth时的三个值，为了方便在文件中修改使用@Value标签定义
    private String giteeClientId;
    @Value("${gitee.client.secret}")
    private String giteeClientSecret;
    @Value("${gitee.redirect.uri}")
    private String giteeRedirectUri;

    /***
     * 实现github三方登陆
     * @param code
     * @param state
     * @param response
     * @return
     */
    @GetMapping("/callback")
    public  String callback(@RequestParam(name = "code") String code,
                            @RequestParam(name = "state")String state,
                            HttpServletResponse response
                          ){
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO(); //设置token的值
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setState(state);
        String accessToken = githubProvider.getAccessToken(accessTokenDTO);
        GithubUser githubUser = githubProvider.getUser(accessToken);
        if( githubUser != null){ //判断用户是否存在
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(githubUser.getName());
            user.setAccountId(String.valueOf(githubUser.getId()));
            user.setBio(githubUser.getBio());
            user.setAvatarUrl(githubUser.getAvatarUrl());
            userService.createOrUpdate(user);//数据插入到本地数据库
            response.addCookie(new Cookie("token",token));
            try {
                response.sendRedirect("/");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "redirect:/";
        }else {
            return "redirect:/";
        }
    }

    /***
     * 实现gitee三方登陆
     * @param code
     * @param response
     * @return
     */
    @GetMapping("/giteecallback")
    public  String giteeCallback(@RequestParam(name = "code") String code,
                            HttpServletResponse response
    ){
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO(); //设置token的值
        accessTokenDTO.setClient_id(giteeClientId);
        accessTokenDTO.setClient_secret(giteeClientSecret);
        accessTokenDTO.setState("1");
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(giteeRedirectUri);
        String accessToken = giteeProvider.getAccessToken(accessTokenDTO);
        GiteeUser giteeUser = giteeProvider.getUser(accessToken);
        if( giteeUser != null){ //判断用户是否存在
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(giteeUser.getName());
            user.setAccountId(String.valueOf(giteeUser.getId()));
            user.setBio(giteeUser.getBio());
            user.setAvatarUrl(giteeUser.getAvatarUrl());
            userService.createOrUpdate(user);//数据插入到本地数据库
            response.addCookie(new Cookie("token",token));
            try {
                response.sendRedirect("/");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "redirect:/";
        }else {
            return "redirect:/";
        }
    }

    /***
     * 退出登陆功能
     * @param response
     * @param request
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletResponse response, HttpServletRequest request){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        try {
            response.sendRedirect("/");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/";
    }


}
